package com.sqx.modules.health.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.Family;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.health.service.IFamilyService;
import com.sqx.modules.health.service.IUserService;
import com.sqx.modules.health.utils.MyBeanUtil;
import com.sqx.modules.health.vo.FamilyVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author gxy
 * @since 2022-05-24
 */

@Api(value = "", tags = "家庭关系表接口", description = "")
@RestController
@RequestMapping("/health/family")
public class FamilyController {
    @Autowired
    private IFamilyService familyService;

    @Autowired
    private IUserService userService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新", notes = "新增或更新")
    public Result save(@RequestBody Family family) {
        return Result.success(familyService.save(family));
    }

    // 根据ID删除
    @GetMapping("/del/{id}")
    @ApiOperation(value = "根据ID删除", notes = "根据ID删除")
    public Result delete(@PathVariable String id) {
        return Result.success(familyService.removeById(id));
    }

    // 根据IDS删除
    @PostMapping("/del/batch")
    @ApiOperation(value = "根据IDS删除", notes = "根据IDS删除")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        return Result.success(familyService.removeByIds(ids));
    }

    // 查询全部
    @GetMapping("/findAll")
    @ApiOperation(value = "查询全部", notes = "查询全部")
    public Result findAll() {
        return Result.success(familyService.list());
    }

    // 根据ID查询一条记录
    @GetMapping("/findOne")
    @ApiOperation(value = "根据ID查询一条记录", notes = "根据ID查询一条记录")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(familyService.getById(id));
    }

    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询", notes = "分页查询")
    public Result findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
        QueryWrapper<Family> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(familyService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

    @ApiOperation(value = "按照身份证号或者手机号查询用户信息", notes = "按照身份证号或者手机号查询用户信息")
    @GetMapping("/findUser")
    public Result findUser(@RequestParam String param) {
        if (StringUtils.isBlank(param)) {
            return Result.error(Constants.CODE_500, "输入参数为空");
        }
        QueryWrapper<SysUserEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("type", 0);
        wrapper.and(userQueryWrapper -> userQueryWrapper.like("phone", param).or().like("username", param));
        SysUserEntity user = userService.getOne(wrapper);
        if (ObjectUtil.isEmpty(user)) {
            return Result.error(Constants.CODE_500, "没有找到指定用户");
        }
        return Result.success(user);
    }

    @ApiOperation(value = "绑定信息", notes = "绑定信息")
    @PostMapping("/banding")
    public Result banding(@RequestBody Family family) {

        if (ObjectUtil.isEmpty(family.getInitiator()) && ObjectUtil.isEmpty(family.getAccepter())) {
            return Result.error(Constants.CODE_500, "绑定人或者被绑定人为空");
        }
        // 判断是否已经进行过绑定
        QueryWrapper<Family> wrapper = new QueryWrapper<>();
        wrapper.eq("initiator", family.getInitiator());
        wrapper.eq("accepter", family.getAccepter());
        if (ObjectUtil.isNotEmpty(familyService.getOne(wrapper))) {
            return Result.error(Constants.CODE_500, "该用户已经和选择用户绑定");
        }
        family.setId(UUID.randomUUID().toString().replace("-", ""));
        family.setFlag("0");
        return Result.success(familyService.save(family));
    }

    @ApiOperation(value = "确认绑定信息", notes = "确认绑定信息")
    @PostMapping("/confirmBanding")
    public Result confirmBanding(@RequestBody Family family) {
        if ("0".equals(family.getFlag())){
            family.setFlag("1");
        }
        return Result.success(familyService.updateById(family));
    }

    @ApiOperation(value = "根据id查询自己的绑定信息(绑定了谁 以及 被谁绑定)", notes = "根据id查询自己的绑定信息(绑定了谁 以及 被谁绑定)")
    @PostMapping("/findBandingDetail")
    public Result findBandingDetail(@RequestBody Map<String, String> params) {
        QueryWrapper<Family> wrapper = new QueryWrapper<>();
        if (params.containsKey("initiator")) {
            wrapper.eq(StringUtils.isNotBlank(params.get("initiator")), "initiator", params.get("initiator"));
        } else if (params.containsKey("accepter")) {
            wrapper.eq(StringUtils.isNotBlank(params.get("accepter")), "accepter", params.get("accepter"));
        } else {
            return Result.error(Constants.CODE_500, "error");
        }
        wrapper.eq("flag", params.get("flag"));
        List<Family> families = familyService.list(wrapper);
        if (families.size() == 0) {
            return Result.success(families);
        }
        List<FamilyVo> familyVos = MyBeanUtil.collectionCopy(families, FamilyVo.class);
        SysUserEntity user;
        if (params.containsKey("initiator")) {
            for (FamilyVo familyVo : familyVos) {
                user = getUserById(familyVo.getAccepter());
                familyVo.setAccepterName(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
                familyVo.setAvatarUrl(user.getAvatarUrl());
                familyVo.setPhone(user.getPhone());
                familyVo.setCardNo(user.getCardid());
                familyVo.setGender(user.getGender());
            }
        } else if (params.containsKey("accepter")) {
            for (FamilyVo familyVo : familyVos) {
                user = getUserById(familyVo.getInitiator());
                familyVo.setAccepterName(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
                familyVo.setAvatarUrl(user.getAvatarUrl());
                familyVo.setPhone(user.getPhone());
                familyVo.setCardNo(user.getCardid());
                familyVo.setGender(user.getGender());
            }
        }
        return Result.success(familyVos);
    }

    private SysUserEntity getUserById(Long uid) {
        return userService.getById(uid);
    }


}

